<template>
  <div class="contant-box">
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      :rules="rules"
      label-width="80px"
      class="demo-ruleForm"
    >
      <el-form-item label="起始节点" prop="start">
        <el-select
          v-model="ruleForm.start"
          filterable
          clearable
          placeholder="请选择"
        >
          <el-option
            v-for="item in nodes"
            :key="item.id"
            :label="item.label"
            :value="item.id"
          />
        </el-select>
        <el-icon class="edit-icon" @click="selectNode(true)">
          <Edit size="20*20" />
        </el-icon>
      </el-form-item>
      <el-form-item label="目标节点" prop="end">
        <el-select
          v-model="ruleForm.end"
          filterable
          clearable
          placeholder="请选择"
        >
          <el-option
            v-for="item in nodes"
            :key="item.id"
            :label="item.label"
            :value="item.id"
          />
        </el-select>
        <el-icon class="edit-icon" @click="selectNode(false)">
          <Edit size="20*20" />
        </el-icon>
      </el-form-item>
      <el-button type="primary" style="width: 100%" @click="search"
        >查询路径</el-button
      >

      <div class="all-path-div">
        <div class="expend-div" v-for="(item, index) in pathArr" :key="index">
          <div class="head" @click="item.expendIcon = !item.expendIcon">
            <span>
              <el-icon
                class="triangle"
                :class="item.expendIcon ? 'is-expend' : ''"
                ><CaretRight
              /></el-icon>
              <span>路径{{ index + 1 }}</span>
            </span>
            <span @click.stop>
              <el-switch v-model="item.switch" @change="showPath" />
            </span>
          </div>
          <div class="expend-contant" v-show="item.expendIcon">
            <el-timeline>
              <el-timeline-item
                v-for="(activity, ind) in item.nodesModel"
                :key="ind"
                :hollow="true"
                type="primary"
              >
                {{ activity.label }}
              </el-timeline-item>
            </el-timeline>
          </div>
        </div>
      </div>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
// vue
import { emitter } from "@/utils/mitt"; // 组件通讯
import { Algorithm } from "@antv/g6";
import { findShortestPath } from "@antv/algorithm"; //"@antv/algorithm": "0.1.26-beta.0",下载试行包后续发正式包后一样，可以获取到边的路径，方便页面上开关展示某条边（正式包只有路径节点）

// 组件
import { ElMessage } from "element-plus";
import { Edit, CaretRight } from "@element-plus/icons-vue";
import { useCanvasStoreHook } from "@/stores/modules/canvas"; // 画布
import { clearAllStats } from "@/views/associationAnalysis/canvas/components/canvasG6/common/index";

const useCanvasStore = useCanvasStoreHook(); // 画布

const graphModule = inject("graphModule");

const ruleFormRef = ref(null);
const ruleForm = reactive({
  start: "",
  end: "",
});

const rules = reactive({
  start: [{ required: true, message: "请填写起点节点", trigger: "blur" }],
  end: [{ required: true, message: "请填写终点节点", trigger: "blur" }],
});

const nodes = useCanvasStore.getCanvasByData().nodes;
console.log(useCanvasStore.getCanvasByData(), 9999);

let isStart = ref(null);
/** 选择节点 */
const selectNode = (value) => {
  isStart.value = value;
  emitter.emit("pathSelectNode", true);
};

/** 获取到选择的节点 */
emitter.on("getPathSelectNode", (node) => {
  isStart.value
    ? (ruleForm.start = node._cfg.model.id)
    : (ruleForm.end = node._cfg.model.id);
  // console.log(ruleForm, "ruleForm", node);
});

/** pathArr数据结构
 * [
      {
        switch: true, // 开关需要
        expendIcon: false, // 折叠图标需要
        nodesModel: [{}],
        nodes: [{}], // node节点数组
        pathIds: ['A', 'D', 'F', 'E'] // 路径所有id
        pathEdgeIds: ['A', 'D', 'E'], // 路径线路边所有id
      },
    ];
 */
const pathArr = ref([]); // 所有路径
/** 查询路径 */
const search = () => {
  pathArr.value = [];
  ruleFormRef.value.validate((valid, fields) => {
    if (valid) {
      // const { findAllPath, findShortestPath } = Algorithm;
      // path最短路径node，edgePath最短路径边路径
      const { allPath, allEdgePath, path, edgePath } = findShortestPath(
        useCanvasStore.getCanvasByData(),
        ruleForm.start,
        ruleForm.end
      ); // 期望输出值allPath：[['A', 'D', 'F', 'E'], ['A', 'D', 'E'], ['A', 'E']]
      console.log(allPath, "allPath", ruleForm, allEdgePath);
      pathArr.value = allPath
        ? allPath.map((item, index) => {
            return {
              switch: true,
              expendIcon: false,
              nodesModel: item.map((it) =>
                graphModule.value.findById(it).getModel()
              ),
              nodes: item.map((it) => graphModule.value.findById(it)),
              pathIds: item,
              pathEdgeIds: allEdgePath[index], // 路径的边id
            };
          })
        : [];

      console.log(pathArr.value, "pathArr.value");

      showPath();
    } else {
      console.log("error submit!", fields);
    }
  });
};

/** 高亮显示所有路径 */
const showPath = () => {
  console.log(pathArr.value);
  clearAllStats(); // 清除所有状态

  for (let i = 0; i < pathArr.value.length; i++) {
    if (!pathArr.value[i].switch) continue; // 关闭开关的时候不高亮显示

    pathArr.value[i].pathEdgeIds.forEach((edgeId) => {
      // 对应路径的边高亮
      let edge = graphModule.value.findById(edgeId);
      graphModule.value.setItemState(edge, "highlight", true);
    });
    // console.log(5656, pathArr.value[i], i);
    for (let j = 0; j < pathArr.value[i].nodes.length; j++) {
      // 每个路径的操作
      const pathNode = pathArr.value[i].nodes[j];
      pathNode.toFront();
      graphModule.value.setItemState(pathNode, "highlight", true); // 路径上的节点高亮
    }
  }
};

/**二维数组去重 */
const removeRepeat = (arr) => {
  const obj = {};
  return arr.filter((item) => {
    if (!obj[item.toString()]) {
      obj[item.toString()] = item.toString();
      return item;
    }
  });
};
</script>

<style lang="scss" scoped>
.contant-box {
  height: calc(100% - 36px);

  .edit-icon {
    margin-left: 20px;
    font-size: 20px;
    cursor: pointer;
  }
}

.all-path-div {
  max-height: calc(100vh - 430px);
  overflow: auto;
}

.expend-div {
  margin: 10px 0 0;

  .head {
    display: flex;
    align-items: center;
    justify-content: space-between;
    cursor: pointer;

    .triangle {
      margin-right: 20px;
      vertical-align: baseline;
      transition: all 0.4s;
    }

    .is-expend {
      transform: rotate(90deg);
    }
  }

  .expend-contant {
    margin: 20px 0 0 10px;
  }
}
</style>
